package org.ithang.tools.eth;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.ithang.application.bcAddr.bean.Block;
import org.ithang.application.bcAddr.bean.BlockResult;
import org.ithang.tools.database.BaseDao;
import org.ithang.tools.lang.JsonUtils;
import org.ithang.tools.model.HttpTools;
import org.ithang.tools.redis.Keys;

/**
 * 以太坊功能
 *@author zyt
 *
 */
public class ETHUtil {

	private final static String ETH_HOST="23.234.3.127";
	
    private final static String ETH_PORT="8989";
	
	//创建以太坊钱包地址
	private final static String CreateWalletURL="/api/account/createwallet";
	
	//查询地址代币余额(Token)
	private final static String TokenBalanceURL="/api/contract/tokenBalance";
	
	private final static String ETHBalanceURL="/api/account/getBalance";
	
	//转账接口地址
	private final static String TransferURL="/api/transaction/token";
	
	//转账eth接口
	private final static String TransferETHURL="/api/transaction/eth";
	
	private final static String DetailURL="/api/transaction/detail";
	
	private final static String CheckAccount="/api/account/checkAccount";
	
	public final static String TestTokenAddress="0x64b6ea1475203ab4fbba9d72eba3e07a63b2685d";
	
	private final static String TokenAddress="0xdac17f958d2ee523a2206206994597c13d831ec7";
	
	private static Logger logger=Logger.getLogger(ETHUtil.class);
	
	/**
	 * 创建钱包地址
	 * @return
	 */
	public static ETHInfo createWallet(){
		String content=HttpTools.doGet("http://"+ETH_HOST+":"+ETH_PORT+CreateWalletURL);
		return JsonUtils.parseJson(content, ETHInfo.class);
	}
	
	/**
	 * 获得最新余额信息
	 * @param address
	 * @return
	 */
	public static double getTokenBalance(String address,boolean test){
		try{
			
			String token=TokenAddress;
			    if(test){
			    	token=TestTokenAddress;
			    }
		String content=HttpTools.doGet("http://"+ETH_HOST+":"+ETH_PORT+TokenBalanceURL+"?address="+address+"&tokenaddress="+token);
		if(null!=content&&content.trim().length()>0){
			ETHInfo ei=JsonUtils.parseJson(content, ETHInfo.class);
			if(null!=ei){
				Map<String,String> data=ei.getData();
				if(null!=data&&!data.isEmpty()){
					return Double.valueOf(data.get("balance"));
				}
			}
		}
		}catch(Exception e){
			logger.error("address:"+address+"\n"+e.getMessage());
			e.printStackTrace();
		}
		
		return 0.0D;
	}
	
	/**
	 * 获得最新余额信息
	 * @param address
	 * @return
	 */
	public static String getETHBalance(String address){
		try{
		String content=HttpTools.doGet("http://"+ETH_HOST+":"+ETH_PORT+ETHBalanceURL+"?address="+address);
		if(null!=content&&content.trim().length()>0){
			ETHInfo ei=JsonUtils.parseJson(content, ETHInfo.class);
			if(null!=ei){
				Map<String,String> data=ei.getData();
				if(null!=data&&!data.isEmpty()){
					return data.get("balance");
				}
			}
		}
		}catch(Exception e){
			logger.error("address:"+address+"\n"+e.getMessage());
			e.printStackTrace();
		}
		
		return "0.0";
	}
	
	
	
	/**
	 * 转账USDT
	 * @param prikey
	 * @param toAddr
	 * @param amout
	 * @return
	 */
	public static ETHInfo transfer(String prikey,String toAddr,double amount,boolean test){
		
		String token=TokenAddress;
		try{
			if(test){
		    	token=TestTokenAddress;
		    }
		}catch(Exception e){
			e.printStackTrace();
		}
		
		Map<String,Object> params=new HashMap<>();
		params.put("private_key", prikey);
		params.put("token_address", token);
		params.put("to_address", toAddr);
		params.put("value", String.valueOf(amount));
		String content=HttpTools.doJSONPost("http://"+ETH_HOST+":"+ETH_PORT+TransferURL, params);
		if(null!=content&&content.trim().length()>0){
			ETHInfo tr=JsonUtils.parseJson(content, ETHInfo.class);
			return tr;
		}
		return null;
	}
	
	/**
	 * 转账
	 * @param prikey
	 * @param toAddr
	 * @param amout
	 * @return
	 */
	public static ETHInfo transferETH(String prikey,String toAddr,double amount){
		Map<String,Object> params=new HashMap<>();
		params.put("private_key", prikey);
		params.put("to_address", toAddr);
		params.put("value", String.valueOf(amount));
		String content=HttpTools.doJSONPost("http://"+ETH_HOST+":"+ETH_PORT+TransferETHURL, params);
		if(null!=content&&content.trim().length()>0){
			ETHInfo tr=JsonUtils.parseJson(content, ETHInfo.class);
			return tr;
		}
		return null;
	}
	
	/**
	 * 查询交易详情
	 * @param txhash
	 * @return
	 */
	public static ETHInfo detail(String txhash){
		String content=HttpTools.doGet("http://"+ETH_HOST+":"+ETH_PORT+DetailURL+"?txhash="+txhash);
		if(null!=content&&content.trim().length()>0){
			ETHInfo ei=JsonUtils.parseJson(content, ETHInfo.class);
			return ei;
		}
		return null;
	}
	
	/**
	 * 检测是否是以太坊地址
	 * @param addr
	 * @return
	 */
	public static boolean checkAccount(String addr){
		try{
		String content=HttpTools.doGet("http://"+ETH_HOST+":"+ETH_PORT+CheckAccount+"?address="+addr);
		if(null!=content&&content.trim().length()>0){
			ETHInfo ei=JsonUtils.parseJson(content, ETHInfo.class);
			if(null!=ei&&null!=ei.getData()&&!ei.getData().isEmpty()){
				return Boolean.valueOf(ei.getData().get("result"));
			}
		}
		}catch(Exception e){
			logger.error("checkAccount about addr:"+addr+"  error !");
			e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 获得交易记录
	 * @param addr
	 * @param test
	 * @return
	 */
	public static List<Block> list(String addr,boolean test){
		String token=TokenAddress;
		String host="http://api.etherscan.io/api";//国外正式模式
		try{
			if(test){//测试模式
		    	token=TestTokenAddress;
		    	host="http://api-ropsten.etherscan.io/api";
		    }
			
			String content=HttpTools.doGet(host+"?module=account&action=tokentx&contractaddress"+token+"&address="+addr+"&sort=desc&apikey=21WPUVQUD9GTVB1ADJRHXMSJ9MMXTZ1MBR");
			if(null!=content&&content.trim().length()>0){
				BlockResult br=JsonUtils.parseJson(content, BlockResult.class);
				if(null!=br&&"1".equals(br.getStatus())){
					return br.getResult();
				}
			}
			
			if(!test){//中国正式模式
				host="http://api-cn.etherscan.com/api";
				content=HttpTools.doGet(host+"?module=account&action=tokentx&contractaddress"+token+"&address="+addr+"&sort=desc&apikey=21WPUVQUD9GTVB1ADJRHXMSJ9MMXTZ1MBR");
				if(null!=content&&content.trim().length()>0){
					BlockResult br=JsonUtils.parseJson(content, BlockResult.class);
					if(null!=br&&"1".equals(br.getStatus())){
						return br.getResult();
					}
				}
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return null;
	}
	
	public static ETHInfo getDetail(String txhash,boolean test){
		String host="https://api.etherscan.io/api";//国外正式模式
		try{
			if(test){//测试模式
		    	host="http://api-ropsten.etherscan.io/api";
		    }
			
			String content=HttpTools.doGet(host+"?module=transaction&action=gettxreceiptstatus&txhash="+txhash+"&apikey=21WPUVQUD9GTVB1ADJRHXMSJ9MMXTZ1MBR");
			if(null!=content&&content.trim().length()>0){
				ETHInfo ei=JsonUtils.parseJson(content, ETHInfo.class);
				return ei;
			}
			
			
			if(!test){//中国正式模式
				host="http://api-cn.etherscan.com/api";
				content=HttpTools.doGet(host+"?module=transaction&action=gettxreceiptstatus&txhash="+txhash+"&apikey=21WPUVQUD9GTVB1ADJRHXMSJ9MMXTZ1MBR");
				if(null!=content&&content.trim().length()>0){
					ETHInfo ei=JsonUtils.parseJson(content, ETHInfo.class);
					return ei;
				}
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return null;
	}
	
	
}
